class RapidshareFreePlugin:
	def __init__(self):
		# put all the links this plugins supports here - it will be used to filter supported URLs
		self.supported_sites = ['rapidshare.com']
		self.supported_urls = ['//rapidshare.com', 'www.rapidshare.com']
		self.cookies_to_block = []
		# whether we support pause/resume
		self.supports_resume = False
		# maximum number of concurrent downloads
		self.max_concurrent = 1
		# parameter names we require
		self.param_names = []
		# parameter values
		self.param_vals = {}
		self.name = 'rapidshare free'

	def get(self, url):
		"""Get a file from rapidshare using the free link"""
		while True:
			sleep_time = self.get_link(url)
			if sleep_time == 0:
				break
			if not sleep_interruptible(sleep_time):
				return

	def get_link(self, url):
		data = get_url_data(url)
		parser = FormLister()
		parser.feed(data)
                my_form = None
		for form in parser.forms:
			if form.id == 'ff':
				my_form = form
				break

		if not my_form:
			for line in data.splitlines():
				if 'automatically deleted' in line or 'The uploader has removed this file' in line:
					raise CantDownload('Error occured while trying to download: file deleted')
				#elif 'You are not signed in' in line:
				#	if not sleep_interruptible(16 * 60):
				#		return
				#	raise TemporarilyUnavailable('Temporary error')

			raise CantDownload('Error occured while trying to download')

		data = get_url_data(form.action, True, my_form.vars, url)
		parser.close()

		sleep_time = 0
		for line in data.splitlines():
			if 'var c' in line:
				sleep_time = get_js_var(line)
			elif 'input checked type' in line:
				url = line.split("\\'")[1]
			elif 'Please try again' in line:
				sleep_time = int(line.split('again in')[1].split('minutes')[0].strip()) * 60
			elif 'We regret that currently we' in line:
				sleep_time = int(line.split('will have to wait')[1].split('minutes')[0].strip()) * 60
			elif 'Or try again in about' in line:
				secs, units = line.split('Or try again in about')[-1].strip().split('.')[0].split()
				if 'second' in units:
					sleep_time = int(secs)
				elif 'minute' in units:
					sleep_time = int(secs) * 60
				if sleep_time == 0:
					raise CantDownload('Error occured while trying to download: sleep time not found')
				return sleep_time
			elif 'uploader has removed' in line:
				raise CantDownload('Error occured while trying to download: file removed')
			elif 'There are no more download slots available' in line:
				if not sleep_interruptible(2 * 60):
					return
				raise TemporarilyUnavailable('No available slots')
			elif 'is already downloading a file' in line:
				if not sleep_interruptible(2 * 60):
					return
				raise TemporarilyUnavailable('Already downloading from this IP')
			#elif 'You are not signed in' in line:
			#	if not sleep_interruptible(16 * 60):
			#		return
			#	raise TemporarilyUnavailable('Temporary error')

		if sleep_time == 0:
			raise TemporarilyUnavailable('Error occured while trying to download: sleep time not found')

		if not sleep_interruptible(sleep_time):
			return

		form_data = {}
		form_data['mirror'] = 'on'
		form_data['x'] = '41'
		form_data['y'] = '61'
		local_file = get_filename_from_url(url)
		content = download_file_with_retries(local_file, url, True, form_data, form.action)
		if content == "application/octet-stream":
			config.report.report_finish(local_file)
		else:
			raise CantDownload("File %s is not what was expected (%s)" % (local_file, content))
		return 0

	def url_matches(self, url):
		"""Check whether we support this URL"""
		for l in self.supported_urls:
			if l in url:
				return True
		return False

	def version(self):
		"""Return plugin version - when interface changes, the version changes"""
		return 2

modules = [RapidshareFreePlugin()]
